package com.heo.util;

import java.util.Map;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.apache.log4j.Logger;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

public class DeviceNettyUtils {

	
	private static Logger log = Logger.getLogger(DeviceNettyUtils.class);
	
	private static ScriptEngine engine;
	
	static {
		engine = new ScriptEngineManager().getEngineByName("JavaScript"); 
	}
	
	public static void deviceInitResult(Map<String, Object> rspJsonMap) {
		rspJsonMap.put("t", 140); // 心跳时间
		rspJsonMap.put("n", 2); // 心跳次数重启
		rspJsonMap.put("v", 2); // 获取指令v*10秒没有检测到启动就重启
		rspJsonMap.put("y", 2); // y // 数据类型：数值，长度小于7字符，描述：连续投币延时时间，单位=秒，分辨率1秒，默认10秒
		rspJsonMap.put("i", 10); // 心跳超时时间
	}
	
	/**
	 * 字符集;分割  获取其中某个
	 * @param scriptEngineCmd
	 * @param size
	 * @return
	 */
	public static String getArrayString(String scriptEngineCmd, int size) {
		if(Utils.checkNull(scriptEngineCmd)) {
			String[] scriptEngineCmds = scriptEngineCmd.split(";");
			if(scriptEngineCmds.length >= (size + 1)) {
				return scriptEngineCmds[size];
			}
		}
		return "";
	}
	
	public static String scriptEngineCmd(String exec, String cmd) throws Exception {
		if(!Utils.checkNull(exec)) {
			return "";
		}
		Compilable compilable = (Compilable) engine;  
		Bindings bindings = engine.createBindings(); // Local级别的Binding  
		CompiledScript jSFunction = compilable.compile(exec); // 解析编译脚本函数  
        bindings.put("cmd", cmd);  
        Object resultJs = jSFunction.eval(bindings);  
        return Utils.getStr(resultJs);
	}
	
	/**
	 * 
	 * @param ctx
	 * @param packet
	 */
	public static void sendMessage(Channel channel, String deviceImei, String rspJson) {
		if(channel.isActive() && channel.isWritable()) {
			channel.writeAndFlush(rspJson + "\n").addListener(new ChannelFutureListener() {
				// 数据发送完毕后，触发本事件
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					log.info("deviceImei=" + deviceImei + ", send message = " + rspJson + "消息发送结果=" + future.isSuccess());
				}
			});
		}
	}
}
